package org.example.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.example.utils.LogUtils;

/**
 * http回显服务器
 */
public class HttpEchoServer {

    public static void main(String[] args) throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();

        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        // 设置bytebuf的分配器
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootstrap.group(bossGroup, workerGroup);

        // 异步线程池，每个任务一个线程
        final EventExecutorGroup executorA = new DefaultEventExecutorGroup(32);

        try {
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // http的解码编码器
                    ch.pipeline().addLast(new HttpRequestDecoder());
                    ch.pipeline().addLast(new HttpResponseEncoder());
                    ch.pipeline().addLast(new HttpObjectAggregator(65535));
                    // 异步线程进行回写
                    // ch.pipeline().addLast(executorA, new HttpBusinessHandler());
                    ch.pipeline().addLast(executorA, new HttpBusinessHandler2());
                }
            });
            bootstrap.localAddress(8082);
            ChannelFuture channelFuture = bootstrap.bind().sync();
            LogUtils.info("服务器启动成功");

            channelFuture.channel().closeFuture().sync();
            LogUtils.info("服务器关闭");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
